﻿Namespace Globals

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Class ErrorHandler

        Public Shared Sub UnhandledException(sender As Object, args As System.UnhandledExceptionEventArgs)

            'Handles any error not handled by a Try Catch statement

            Dim err_file As String = "error.txt"
            Dim err_path As String = Globals.sServerPath & "\"
            Dim it As Integer
            Do Until Not System.IO.File.Exists(err_path & err_file)
                it += 1
                err_file = "error-(" & it & ").txt"
            Loop

            Dim FS As System.IO.FileStream = New System.IO.FileStream(err_path & err_file, System.IO.FileMode.OpenOrCreate)
            Dim BW As System.IO.BinaryWriter = New System.IO.BinaryWriter(FS)

            BW.Write(vbCrLf & vbCrLf & "[============================================================================================================]" & vbCrLf & vbCrLf)

            BW.Write("==[ " & DateTime.Now.ToString & " ]==" & vbCrLf & vbCrLf)
            BW.Write("Error Message: " & args.ExceptionObject.Message & vbCrLf & vbCrLf)
            BW.Write("Source: " & args.ExceptionObject.Source & vbCrLf)
            BW.Write("Target Site: " & args.ExceptionObject.TargetSite.Name & vbCrLf)
            BW.Write("Stack trace follows... " & vbCrLf & args.ExceptionObject.StackTrace & vbCrLf)

            BW.Write(vbCrLf & vbCrLf & "[============================================================================================================]" & vbCrLf & vbCrLf)

            BW.Flush()
            BW.Close()

        End Sub

    End Class


End Namespace
